using System.Linq;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using JGSY.AI.DesktopUI.Services;
using System.Collections.Generic;
using System;

namespace JGSY.AI.DesktopUI.ViewModels;

public partial class SettingsViewModel : ViewModelBase
{
    public event EventHandler? CloseRequested;
    [ObservableProperty]
    private ThemeInfo? _selectedTheme;

    [ObservableProperty]
    private bool _startMaximized = false;

    [ObservableProperty]
    private bool _startMinimized = false;

    public bool IsNormalWindow
    {
        get => !StartMaximized && !StartMinimized;
        set
        {
            if (value)
            {
                StartMaximized = false;
                StartMinimized = false;
            }
        }
    }

    [ObservableProperty]
    private bool _rememberPosition = true;

    [ObservableProperty]
    private bool _minimizeToTray = false;

    private readonly IThemeService _themeService;

    public IEnumerable<ThemeInfo> AvailableThemes => _themeService.GetAvailableThemes();

    public ICommand ResetThemeCommand { get; }
    public ICommand CloseCommand { get; }

    public SettingsViewModel()
    {
        _themeService = App.ThemeService;
        
        // 找到当前主题对应的ThemeInfo
        SelectedTheme = _themeService.GetAvailableThemes()
            .FirstOrDefault(t => t.Name == _themeService.CurrentTheme);
        
        ResetThemeCommand = new RelayCommand(OnResetTheme);
        CloseCommand = new RelayCommand(OnClose);
    }

    // 当选择的主题改变时自动应用
    partial void OnSelectedThemeChanged(ThemeInfo? value)
    {
        if (value != null)
        {
            _themeService.ApplyTheme(value.Name);
        }
    }

    // 窗口状态互斥逻辑
    partial void OnStartMaximizedChanged(bool value)
    {
        if (value && StartMinimized)
        {
            StartMinimized = false;
        }
    }

    partial void OnStartMinimizedChanged(bool value)
    {
        if (value && StartMaximized)
        {
            StartMaximized = false;
        }
    }

    private void OnResetTheme()
    {
        SelectedTheme = _themeService.GetAvailableThemes()
            .FirstOrDefault(t => t.Name == "ModernBlue");
    }

    private void OnClose()
    {
        CloseRequested?.Invoke(this, EventArgs.Empty);
    }
}
